package com.aloda.service.impl;

import com.aloda.constant.MessageConstant;
import com.aloda.constant.UserConstant;
import com.aloda.context.BaseContext;
import com.aloda.dto.AddressAddDTO;
import com.aloda.entity.Address;
import com.aloda.exception.AddressException;
import com.aloda.mapper.AddressMapper;
import com.aloda.service.AddressService;
import com.aloda.vo.AddressInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 新增地址
     *
     * @param addressAddDTO
     */
    @Override
    public void addAddress(AddressAddDTO addressAddDTO) {
        Long id = BaseContext.getCurrentId();
        //如果该用户的地址超过四条提示地址信息已满，请删除后添加
        if(addressMapper.getAddressNum(id)>= UserConstant.MAX_ADDRESS_NUM){
            throw new AddressException(MessageConstant.ADDRESS_NUM_ERROR);
        }
        Address address = new Address();
        BeanUtils.copyProperties(addressAddDTO,address);
        address.setUserId(id);
        addressMapper.insert(address);
    }

    /**
     * 查询地址
     *
     * @return
     */
    @Override
    public List<AddressInfoVO> queryAddress() {
        Long id = BaseContext.getCurrentId();
        List<Address> list = addressMapper.getAddressByUserId(id);
        List<AddressInfoVO> addressInfoVOList = new ArrayList<>();
        for (Address address : list) {
            String addressInfo = address.getProvinceName()+address.getCityName()+address.getDistrictName();
            AddressInfoVO addressInfoVO = AddressInfoVO.builder()
                    .id(address.getId())
                    .label(address.getLabel())
                    .gender(address.getGender())
                    .phone(address.getPhone())
                    .detail(address.getDetail())
                    .consignee(address.getConsignee())
                    .addressInfo(addressInfo)
                    .build();
            addressInfoVOList.add(addressInfoVO);
        }
        return addressInfoVOList;
    }
}
